package com.jy.appmarket.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.jy.app.market.apk.type.LinkType;
import com.jy.app.market.idata.data.Ad;
import com.jy.app.market.idata.data.LoadingAd;
import com.jy.appmarket.activity.AppDetailActivity;
import com.jy.appmarket.activity.WebViewActivity;
import com.jy.appmarket.newnetwork.Request;
import com.jy.appmarket.newnetwork.RequestQueue;
import com.jy.appmarket.newnetwork.Response.Listener;
import com.jy.appmarket.newnetwork.api.ApiRequest;
import com.jy.appmarket.newnetwork.api.ApiResult;
import com.jy.appmarket.newnetwork.api.MarketApi;
import com.jy.appmarket.statistics.ApkSource;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

public class AdManager implements Listener<ApiResult>, RequestQueue.RequestFinishedListener<ApiResult> {
	private static final String TAG = AdManager.class.getSimpleName();
	public static final String EXTRA_TYPE = "extra_ad_type";
	public static final String EXTRA_URL = "extra_ad_url";
	public static final String EXTRA_SOURCE = "extra_ad_source";

	private static AdManager sInstance = null;
	private List<Ad> mList = new ArrayList<Ad>();
	private Context context;

	private AdManager() {

	}

	public static AdManager instance(Context context) {
		if (sInstance == null) {
			synchronized (AdManager.class) {
				if (sInstance == null) {
					sInstance = new AdManager();
				}
			}
		}
		if (context != null) {
			sInstance.context = context.getApplicationContext();
		}
		return sInstance;
	}

	public Ad getOne() {
		List<Ad> tmp = new ArrayList<Ad>();
		for (Ad ad : mList) {
			File cache = ImageLoader.getInstance().getDiskCache().get(ad.getImage());
			if (cache.exists()) {
				tmp.add(ad);
			}
		}
		if (tmp.isEmpty()) {
			return null;
		}
		int rnd = new Random().nextInt(tmp.size());
		return tmp.get(rnd);
	}

	private RequestQueue mQueue = null;
	private ApiRequest mRequest = null;

	/**
	 * 请求loading_ad广告
	 * 
	 * @param context
	 * @param force
	 *            默认每天请求一次，如果此值为true则强制请求
	 */
	public boolean getAdFromNetwork(boolean force) {
		if (context == null) {
			return false;
		}

		long time = Prefs.getLoadingAdRequestTime(context);
		if (!force && Math.abs(System.currentTimeMillis() - time) < 1000 * 60 * 30) {
			LogUtil.d(TAG, " no need to update");
			return false;
		}

		if (mQueue == null) {
			mQueue = MarketApi.newApiRequestQueue(context);
			mQueue.addRequestFinishedListener(this);
		}
		mRequest = ApiRequest.get("loading_ad", this, null);
		mQueue.add(mRequest);
		return true;
	}

	public boolean executeAd(Activity activity, LinkType type, String url) {
		if (activity == null) {
			return false;
		}
		String source = new ApkSource("loading_ad").toSourceString();
		try {
			if (type == LinkType.App) {
				if (PackageUtils.isPackageInstalled(activity, url)) {
					PackageUtils.launchPackageFromActivity(activity, url);
				} else {
					Intent intent = new Intent(activity, AppDetailActivity.class);
					intent.putExtra(AppDetailActivity.EXTRA_NAME, "");// TODO
					intent.putExtra(AppDetailActivity.EXTRA_PKG, url);
					intent.putExtra(AppDetailActivity.EXTRA_SOURCE, source);
					activity.startActivity(intent);
				}
			} else if (type == LinkType.WebView) {
				Intent intent = new Intent(activity, WebViewActivity.class);
				intent.putExtra(WebViewActivity.EXTRA_TITLE, "");// TODO
				intent.putExtra(WebViewActivity.EXTRA_URL, url);
				activity.startActivity(intent);
			}
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public void onResponse(ApiResult response) {
		if (!response.isOK()) {
			return;
		}

		LoadingAd loadingAd = response.getData(LoadingAd.class);
		if (loadingAd == null) {
			return;
		}
		mList.clear();

		List<Ad> ads = loadingAd.getAds();

		for (Ad ad : ads) {

			mList.add(ad);
			ImageLoader.getInstance().loadImage(ad.getImage(), null);
		}
	}

	@Override
	public void onRequestFinished(Request<ApiResult> request) {
		if (mQueue != null) {
			mQueue.stop();
			mQueue = null;
		}
		Prefs.setLoadingAdRequestTime(context, System.currentTimeMillis());
	}
}
